package com.ziq.zcamp.community

import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.amap.api.location.AMapLocation
import com.blankj.utilcode.util.GsonUtils
import com.ziq.base.extension.launchWithTry
import com.ziq.zcamp.api.request.post.PostingNearbyListParam
import com.ziq.zcamp.api.respond.post.PostingNearbyListRespond
import com.ziq.zcamp.api.service.PostingService
import com.ziq.zcamp.api.service.request
import com.ziq.zcamp.bean.post.ImageInfo
import com.ziq.zcamp.bean.post.PostingNearbyDetail
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.util.MapUtil
import com.ziq.zcamp.view.StatusView
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class CommunityNearbyViewModel @Inject constructor() : ViewModel() {

    @Inject
    lateinit var mPostingService: PostingService

    var location :AMapLocation ? = null
        private set
    private var cursor : String ? = null
    private var hasMore : Boolean = true


    val statusView = MutableLiveData<Int>()
    val hasMoreDate = MutableLiveData<Boolean>()
    val nearbyPostingList = MutableLiveData<MutableList<PostingNearbyDetail>>()


    fun dataRefresh() {
        if (nearbyPostingList.value?.isNotEmpty() != true){
            statusView.value = StatusView.LOADING
        }
        MapUtil.getCurrentLocation(callback = {
            if (it.errorCode == 0){
                location = it
                requestNetworkData(true,it)
            }else{
                statusView.value = CommunityNearbyFragment.STATUS_VIEW_NO_PERMISSIONS
            }
        }, onFail = {
            statusView.value = CommunityNearbyFragment.STATUS_VIEW_NO_PERMISSIONS
            Toast.makeText(GlobalContextManager.appContext!!, "需同意隐私协议！", Toast.LENGTH_SHORT).show()
        })
    }

    fun dataLoadMore(){
        requestNetworkData(false,location)
    }

    private fun requestNetworkData(isFirst : Boolean ,location : AMapLocation?,
                                   onSuccess: ((result: PostingNearbyListRespond) -> Unit)? = {
                                       hasMore = it.data?.has_more?:false
                                       cursor = it.data?.cursor?:""

                                       val tempList = mutableListOf<PostingNearbyDetail>()
                                       if(!isFirst){
                                           tempList.addAll(nearbyPostingList.value!!)
                                       }
                                       it.data?.list?.let { list->
                                           tempList.addAll(list)
                                       }
                                       nearbyPostingList.postValue(tempList)
                                       if (tempList.isEmpty()){
                                           statusView.value = StatusView.NO_DATA
                                       }else{
                                           statusView.value = StatusView.IDLE
                                       }
                                       hasMoreDate.value = hasMore
                                   },
                                   onFail: ((result: String) -> Unit)? = {
                                       if (nearbyPostingList.value?.isNotEmpty() != true){
                                           statusView.value = StatusView.NET_ERROR
                                       }else{
                                           statusView.value = StatusView.IDLE
                                       }
                                   }){
        if (location == null){
            return
        }
        if (isFirst){
            cursor = null
            hasMore = true
            if (nearbyPostingList.value?.isNotEmpty() != true){
                statusView.value = StatusView.LOADING
            }
        }
        if (!hasMore){
            return
        }

        launchWithTry(whenTry = {
            val respond = mPostingService.postingNearbyList(PostingNearbyListParam().apply {
                this@CommunityNearbyViewModel.cursor?.let {
                    this.cursor = it
                }
                this.page_size = 10
                this.latitude = location.latitude.toString()
                this.longitude = location.longitude.toString()
            }.queryMap).request()

            if(respond.data?.list?.isNotEmpty() == true){
                for(item in respond.data?.list!!){
                    item.parseData()
                }
            }

            onSuccess?.invoke(respond)
        }, whenCatch = {
            withContext(Dispatchers.Main) {
                onFail?.invoke("$it")
            }
        })
    }
}